package com.meizhuang.controller;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Strings;
import com.meizhuang.config.CacheUtils;
import com.meizhuang.entity.*;
import com.meizhuang.service.*;
import com.meizhuang.utils.request.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.enums.SystemParameterEnum;
import com.meizhuang.param.request.PageRequest;
import com.meizhuang.result.JsonResult;
import com.meizhuang.result.PageResult;
import com.meizhuang.utils.SystemParameterUtils;
import com.meizhuang.utils.encrypt.MD5;
import com.meizhuang.web.Constants;
import net.coobird.thumbnailator.Thumbnails;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api(tags = "用户相关接口")
public class UserInfoController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private OfferProductService offerProductService;

    @Autowired
    private EntryService entryService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private UserIntegralRecordService userIntegralRecordService;

    @RequestMapping(value = "/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    @RequestMapping(value = "/register")
    public ModelAndView register() {
        return new ModelAndView("register");
    }


    //用户个认信息
    @RequestMapping(value = "/personalInformation")
    public JsonResult personal_information(HttpServletRequest request, HttpServletResponse response) {
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        Map<String, Object> retMap = new HashMap<>();
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        } else {
            UserInfo userInfo = userInfoService.selectById(userSession);
            retMap.put("user", userInfo);
        }

        String opMsg = (String) super.getSession().getAttribute("op_msg");
        if (opMsg != null) {
            retMap.put("msg", opMsg);
            super.getSession().removeAttribute("op_msg");
        }


        return JsonResult.buildSuccess(retMap);

    }

    //用户首页
    @RequestMapping(value = "/userInfo")
    public JsonResult user_info(HttpServletRequest request, HttpServletResponse response) {
//		Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        Map<String, Object> retMap = new HashMap<>();
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        } else {
            UserInfo userInfo = userInfoService.selectById(userSession);
            retMap.put("user", userInfo);
        }

        String type = request.getParameter("type");

        String opMsg = (String) super.getSession().getAttribute("op_msg");
        if (opMsg != null) {
            retMap.put("msg", opMsg);
            retMap.remove("op_msg");
            super.getSession().removeAttribute("op_msg");
        }

//		if("2".equals(type)){
//			return new ModelAndView("personal_information");
//		}

        EntityWrapper<OfferProduct> wrapper = new EntityWrapper<OfferProduct>();
        wrapper.eq("uid", userSession);
        int productInt = offerProductService.selectCount(wrapper);
        retMap.put("productCount", productInt);

        EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
        userIntegralEntityWrapper.eq("uid", userSession);
        UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);
        retMap.put("userIntegral", userIntegral);
        return JsonResult.buildSuccess(retMap);
    }


    //提交注册
    @RequestMapping(value = "/registerDo")
    public JsonResult registerDo(@RequestParam(value = "weixinImg", required = false) MultipartFile multipartFile,//微信二维码
                                 @RequestParam(value = "logoImg", required = false) MultipartFile multipartFile2,//logo

                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        String phone = request.getParameter("phone");//手机号

        String pwd = request.getParameter("pwd");//密码

        String pwd2 = request.getParameter("pwd2");

        String weixin = request.getParameter("weixin");//微信 账号

        String storeName = request.getParameter("storeName");//店名

        String tradeStall = request.getParameter("tradeStall");//市场档口号

        String storeRemark = request.getParameter("storeRemark");//市场档口号

        String verifyCode = request.getParameter("verifyCode");//短信验证码

        request.setAttribute("phone", phone);
        request.setAttribute("pwd", pwd);
        request.setAttribute("pwd2", pwd2);
        request.setAttribute("weixin", weixin);
        request.setAttribute("storeName", storeName);
        request.setAttribute("tradeStall", tradeStall);
        request.setAttribute("storeRemark", storeRemark);


        retMap.put("phone", phone);
        retMap.put("pwd", pwd);
        retMap.put("pwd2", pwd2);
        retMap.put("weixin", weixin);
        retMap.put("storeName", storeName);
        retMap.put("tradeStall", tradeStall);
        retMap.put("storeRemark", storeRemark);

        if (StringUtils.isEmpty(phone)) {
            retMap.put("msg", "手机号不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(pwd)) {
            retMap.put("msg", "密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(pwd2)) {
            retMap.put("msg", "确认密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (!pwd.equals(pwd2)) {
            retMap.put("msg", "密码和确认密码不一致");
            return JsonResult.buildError(retMap);
        }
        String newFileName = null;
        if (multipartFile != null && !multipartFile.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
                if (bi == null) {
                    retMap.put("msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                retMap.put("msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator;

            try {
                InputStream inputStream = multipartFile.getInputStream();
                String fileName = multipartFile.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(newFileName));

                Thumbnails.of(filePath + newFileName).scale(0.7f).toFile(filePath + newFileName);//按比例缩小


            } catch (Exception e) {
                retMap.put("msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }

        }


        String logonewFileName = null;
        if (multipartFile2 != null && !multipartFile2.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile2.getInputStream());
                if (bi == null) {
                    retMap.put("msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                retMap.put("msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator + "logo" + File.separator;

            try {
                InputStream inputStream = multipartFile2.getInputStream();
                String fileName = multipartFile2.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                logonewFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(logonewFileName));
                Thumbnails.of(filePath + logonewFileName).scale(0.7f).toFile(filePath + logonewFileName);//按比例缩小

            } catch (Exception e) {
                retMap.put("msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }


        EntityWrapper<UserInfo> wrapper = new EntityWrapper<UserInfo>();
        wrapper.eq("mobile", phone);

        int count = userInfoService.selectCount(wrapper);

        if (count > 0) {
            retMap.put("msg", "手机号已注册");
            return JsonResult.buildError(retMap);
        }

        String pwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + pwd);

        UserInfo newUser = new UserInfo();
        newUser.setUserType(UserInfo.USER_KIND);
        newUser.setMobile(phone);
        newUser.setPwd(pwdString);
        newUser.setLoginStatus(1);
        newUser.setWeixin(weixin);
        newUser.setWeixinImg(newFileName);
        newUser.setLogoImg(logonewFileName);
        newUser.setTradeStall(tradeStall);
        newUser.setStoreName(storeName);
        newUser.setStoreRemark(storeRemark);
        newUser.setRandom(RandomStringUtils.randomNumeric(9));

        boolean result = userInfoService.insert(newUser);
        if (result) {
            newUser = userInfoService.selectById(newUser.getUid());
            super.getSession().setAttribute(UserInfo.USER_SESSION_UID, newUser.getUid());
            retMap.put("user", newUser);
            return JsonResult.buildSuccess(retMap);
        }
        return JsonResult.buildSuccess(retMap);
    }


    @RequestMapping(value = "/loginDo")
    public JsonResult loginDo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        String phone = request.getParameter("phone");
        String pwd = request.getParameter("pwd");

        EntityWrapper<UserInfo> wrapper = new EntityWrapper<UserInfo>();
        wrapper.eq("mobile", phone);
        List<UserInfo> userList = userInfoService.selectList(wrapper);
        if (userList == null || userList.size() == 0) {
            retMap.put("msg", "用户名或密码错误");
            return JsonResult.buildError(retMap);
        }
        UserInfo userInfo = userList.get(0);

        if (userInfo.getLoginStatus() == 0) {
            retMap.put("msg", "账号禁止登录");
            return JsonResult.buildError(retMap);
        }

        String pwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + pwd);

        if (!pwdString.equals(userInfo.getPwd())) {
            retMap.put("msg", "用户名或密码错误");
            return JsonResult.buildError(retMap);
        }


        super.getSession().setAttribute(UserInfo.USER_SESSION_UID, userInfo.getUid());
        retMap.put("user", userInfo);


        UserInfo upUserInfo = new UserInfo();
        upUserInfo.setUid(userInfo.getUid());
        upUserInfo.setLastLoginTime(new Date());
        upUserInfo.setLoginCookies(UUID.randomUUID().toString());
        userInfoService.updateById(upUserInfo);

        userInfo.setLoginCookies(upUserInfo.getLoginCookies());
        try {
            saveCookie(response, UserInfo.USER_COOKIES_NAME, upUserInfo.getLoginCookies(), 60 * 60 * 24 * 30 * 2);
        } catch (Exception e) {
            logger.error(e.toString());
        }


        String homeDomain = SystemParameterUtils.get(SystemParameterEnum.HOME_DOMAIN_NAME);

        return JsonResult.buildSuccess(retMap);
        //return new ModelAndView("login");
    }


    /**
     * 微信登录API
     * 短信登录注册API
     * LoginRequest
     * @param response
     * @return
     */
    @PostMapping(value = "/wechat/login")
    @ApiOperation(value = "微信登录", notes = "微信登录API")
    public JsonResult wechatLogin(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();


        String url = "https://api.weixin.qq.com/sns/auth";
        Map<String, String> parameters =  new HashMap<>();
        parameters.put("access_token",loginRequest.getAccessToken());
        final JsonResult<String> jsonResult = HttpClientUtil.sendGet(url, parameters, "UTF-8");

        final String data = jsonResult.getData();
        JSONObject jsonObject = new JSONObject(data);
        Integer errcode = (Integer) jsonObject.get("errcode");

        if(!Objects.equals(0,errcode)){
            retMap.put("msg", "请使用正确的微信登录");
            return JsonResult.buildError(retMap);
        }

        if(Objects.equals(1,loginRequest.getLoginType())) {
            //app的话，微信登陆之后，用本地号码作为他的账号

        }else if(Objects.equals(2,loginRequest.getLoginType())){

            //如果小程序登陆，用授权的手机号码作为账号
        }else if (Objects.equals(3,loginRequest.getLoginType())) {
            //手机号登录注册
        }

        EntityWrapper<UserInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", loginRequest.getPhone());
        List<UserInfo> userList = userInfoService.selectList(wrapper);

        if(CollectionUtils.isEmpty(userList)){

            if (Objects.equals(3,loginRequest.getLoginType())) {
                //手机号登录注册 验证验证码

                if (null != CacheUtils.get(SMS_PREFIX + loginRequest.getVerificationCode()) ){
                    retMap.put("msg", "验证码错误");
                    return JsonResult.buildError(retMap);
                }
            }

            UserInfo newUser = new UserInfo();
            newUser.setUserType(UserInfo.USER_KIND);
            newUser.setMobile(loginRequest.getPhone());
            newUser.setLoginStatus(1);
            newUser.setRandom(RandomStringUtils.randomNumeric(9));

            if(StringUtils.isNotBlank(loginRequest.getPassword())) {
                newUser.setPwd(loginRequest.getPassword());
            }
            boolean result = userInfoService.insert(newUser);
            if (result) {
                newUser = userInfoService.selectById(newUser.getUid());
                super.getSession().setAttribute(UserInfo.USER_SESSION_UID, newUser.getUid());
            }
        }else{

            UserInfo userInfo = userList.get(0);
            if (Objects.equals(3,loginRequest.getLoginType())) {
                //手机登录  需要验证密码

                if (!Strings.nullToEmpty(userInfo.getPwd()).equals(loginRequest.getPassword())) {
                    retMap.put("msg", "密码不正确");
                    return JsonResult.buildError(retMap);
                }
            }

        }


        UserInfo userInfo = userList.get(0);
        super.getSession().setAttribute(UserInfo.USER_SESSION_UID, userInfo.getUid());
        retMap.put("user", userInfo);


        UserInfo upUserInfo = new UserInfo();
        upUserInfo.setUid(userInfo.getUid());
        upUserInfo.setLastLoginTime(new Date());
        upUserInfo.setLoginCookies(UUID.randomUUID().toString());
        userInfoService.updateById(upUserInfo);

        userInfo.setLoginCookies(upUserInfo.getLoginCookies());
        try {
            saveCookie(response, UserInfo.USER_COOKIES_NAME, upUserInfo.getLoginCookies(), 60 * 60 * 24 * 30 * 2);
        } catch (Exception e) {
            logger.error(e.toString());
        }

        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 通过code获取open_id
     * @param getOpenId
     * @return
     */
    @PostMapping(value = "/query/openId")
    @ApiOperation(value = "获取openId", notes = "通过code查询openId")
    public JsonResult getOpenId(@RequestBody GetOpenId getOpenId) {

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> parameters =  new HashMap<>();
        parameters.put("appid","wxfa659ca32c6551d3");
        parameters.put("secret","db8f66aa27648b92f91d79de6f2ebaba");
        parameters.put("js_code",Strings.nullToEmpty(getOpenId.getCode()).trim());
        parameters.put("grant_type","authorization_code");
        final JsonResult<String> jsonResult = HttpClientUtil.sendGet(url, parameters, "UTF-8");
        final String data = jsonResult.getMsg();

        JSONObject jsonObject = new JSONObject(data);
        String openid = (String) jsonObject.get("openid");

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("openid",openid);
        return JsonResult.buildSuccess(retMap);
    }

    public String getCookiesValue(String cookieName, HttpServletRequest request){

        String value = request.getHeader(cookieName);
        if(StringUtils.isBlank(value)){
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(cookieName)){
                        value = cookie.getValue();
                    }
                }
            }
        }
        return value;
    }


    @RequestMapping(value = "/autologin")
    public JsonResult autologin(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> retMap = new HashMap<>();

        String cookiesName = getCookiesValue(UserInfo.USER_COOKIES_NAME, request) ;
        if(StringUtils.isNotBlank(cookiesName)){
            EntityWrapper<UserInfo> entity = new EntityWrapper<UserInfo>();
            entity.eq("login_cookies", cookiesName);
            UserInfo userInfo = userInfoService.selectOne(entity);
            if(userInfo != null){
                request.getSession().setAttribute(UserInfo.USER_SESSION_UID, userInfo.getUid());
                request.setAttribute("user", userInfo);
                return JsonResult.buildSuccess(retMap);
            }
        }

        retMap.put("msg", "无效的token,无法完成自动登录");
        return JsonResult.buildError(retMap);
    }


    //退出
    @RequestMapping(value = "/loginOut")
    public JsonResult loginOut(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        super.getSession().removeAttribute(UserInfo.USER_SESSION_UID);
        saveCookie(response, UserInfo.USER_COOKIES_NAME, null, 0);
        super.getSession().invalidate();

        String homeDomain = SystemParameterUtils.get(SystemParameterEnum.HOME_DOMAIN_NAME);
        return JsonResult.buildSuccess(retMap);
    }


    //更新个人信息
    @RequestMapping(value = "/upUserInfo")
    public JsonResult upUserInfo(@RequestParam(value = "weixinImg", required = false) MultipartFile multipartFile,//个人微信二维码
                                 @RequestParam(value = "logoImg", required = false) MultipartFile multipartFile2,//logo
                                 @RequestParam(value = "location", required = false) MultipartFile multipartFile3,//logo
                                 @RequestParam(value = "license", required = false) MultipartFile multipartFile4,//logo
                                 @RequestParam(value = "background", required = false) MultipartFile multipartFile5,//logo
                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        String weixin = request.getParameter("weixin");
        String storeName = request.getParameter("storeName");
        String tradeStall = request.getParameter("tradeStall");
        String signature = request.getParameter("signature");
        String storeRemark = request.getParameter("storeRemark");

        UserInfo userInfo = null;
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        } else {
            userInfo = userInfoService.selectById(userSession);
            retMap.put("user", userInfo);
        }

        if (userInfo == null) {
            retMap.put("msg", "用户不存在");
            return JsonResult.buildError(retMap);
        }
        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());


        String newFileName = null;
        if (multipartFile != null && !multipartFile.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
                if (bi == null) {
                    retMap.put("op_msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("op_msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                retMap.put("op_msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator;

            try {
                InputStream inputStream = multipartFile.getInputStream();
                String fileName = multipartFile.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(newFileName));
                Thumbnails.of(filePath + newFileName).scale(0.7f).toFile(filePath + newFileName);//按比例缩小

            } catch (Exception e) {
                retMap.put("op_msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }


        String logonewFileName = null;
        if (multipartFile2 != null && !multipartFile2.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile2.getInputStream());
                if (bi == null) {
                    retMap.put("op_msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("op_msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                request.setAttribute("op_msg", "未配置filePath");
                retMap.put("op_msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator + "logo" + File.separator;

            try {
                InputStream inputStream = multipartFile2.getInputStream();
                String fileName = multipartFile2.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                logonewFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(logonewFileName));
                Thumbnails.of(filePath + logonewFileName).scale(0.7f).toFile(filePath + logonewFileName);//按比例缩小

            } catch (Exception e) {
                retMap.put("op_msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }



        String logonewFileName3 = null;
        if (multipartFile3 != null && !multipartFile3.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile3.getInputStream());
                if (bi == null) {
                    retMap.put("op_msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("op_msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                request.setAttribute("op_msg", "未配置filePath");
                retMap.put("op_msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator + "logo" + File.separator;

            try {
                InputStream inputStream = multipartFile3.getInputStream();
                String fileName = multipartFile3.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                logonewFileName3 = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(logonewFileName3));
                Thumbnails.of(filePath + logonewFileName3).scale(0.7f).toFile(filePath + logonewFileName3);//按比例缩小

            } catch (Exception e) {
                retMap.put("op_msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }



        String logonewFileName4 = null;
        if (multipartFile4 != null && !multipartFile4.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile4.getInputStream());
                if (bi == null) {
                    retMap.put("op_msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("op_msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                request.setAttribute("op_msg", "未配置filePath");
                retMap.put("op_msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator + "logo" + File.separator;

            try {
                InputStream inputStream = multipartFile4.getInputStream();
                String fileName = multipartFile4.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                logonewFileName4 = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(logonewFileName4));
                Thumbnails.of(filePath + logonewFileName4).scale(0.7f).toFile(filePath + logonewFileName4);//按比例缩小

            } catch (Exception e) {
                retMap.put("op_msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }



        String logonewFileName5 = null;
        if (multipartFile5 != null && !multipartFile5.isEmpty()) {
            // 检查是否是图片
            try {
                BufferedImage bi = ImageIO.read(multipartFile5.getInputStream());
                if (bi == null) {
                    retMap.put("op_msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }
            } catch (IOException e) {
                retMap.put("op_msg", "请上传图片格式的文件");
                return JsonResult.buildError(retMap);
            }

            String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

            if (StringUtils.isBlank(filePath)) {
                request.setAttribute("op_msg", "未配置filePath");
                retMap.put("op_msg", "未配置filePath");
                return JsonResult.buildError(retMap);
            }
            filePath = filePath + File.separator + "logo" + File.separator;

            try {
                InputStream inputStream = multipartFile5.getInputStream();
                String fileName = multipartFile5.getOriginalFilename();
                Path directory = Paths.get(filePath);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                logonewFileName5 = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                long copy = Files.copy(inputStream, directory.resolve(logonewFileName5));
                Thumbnails.of(filePath + logonewFileName5).scale(0.7f).toFile(filePath + logonewFileName5);//按比例缩小

            } catch (Exception e) {
                retMap.put("op_msg", "图片上传失败");
                return JsonResult.buildError(retMap);
            }
        }


        UserInfo upUserInfo = new UserInfo();
        upUserInfo.setUid(userInfo.getUid());
        upUserInfo.setWeixin(weixin);
        upUserInfo.setStoreName(storeName);
        upUserInfo.setTradeStall(tradeStall);
        upUserInfo.setStoreRemark(storeRemark);

        if(StringUtils.isNotBlank(signature)){
            upUserInfo.setSignature(signature);
        }
        if (newFileName != null) {
            upUserInfo.setWeixinImg(newFileName);
        }
        if (logonewFileName != null) {
            upUserInfo.setLogoImg(logonewFileName);
        }



        if (logonewFileName3 != null) {
            upUserInfo.setLocation(logonewFileName3);
        }
        if (logonewFileName4 != null) {
            upUserInfo.setLicense(logonewFileName4);
        }
        if (logonewFileName5 != null) {
            upUserInfo.setBackground(logonewFileName5);
        }
        userInfoService.updateById(upUserInfo);

        request.getSession().setAttribute("op_msg", "更新成功");
        retMap.put("op_msg", "更新成功");
        return JsonResult.buildSuccess(retMap);
    }

    //上传报价
    @RequestMapping(value = "/uploadProduct")
    public JsonResult uploadProduct(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());

        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }
        return JsonResult.buildSuccess(retMap);
    }

    //报价管理
    @RequestMapping(value = "/productManage")
    public JsonResult productManage(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());

        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }
        return JsonResult.buildSuccess(retMap);
    }

    @RequestMapping(value = "/productManageList")
    public PageResult<OfferProduct> productManageList(PageRequest pageRequest, HttpServletRequest request, HttpServletResponse response) {
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            return PageResult.buildError("请登录");
        }

        Page<OfferProduct> page = new Page<OfferProduct>(pageRequest.getPage(), pageRequest.getLimit() * 10, pageRequest.getSortField(), pageRequest.getAscState());

        String sctime = request.getParameter("sctime");

        EntityWrapper<OfferProduct> wrapper = new EntityWrapper<OfferProduct>();
        wrapper.eq("uid", userSession);
        if (StringUtils.isNotEmpty(sctime)) {
            String[] ctime = sctime.split("~");
            if (ctime.length == 2) {
                wrapper.ge("ctime", ctime[0]);
                wrapper.le("ctime", ctime[1]);
            }
        }


        // 查询数据返回总记录数和数据
        offerProductService.selectPage(page, wrapper);

        List<OfferProduct> records = page.getRecords();
        UserInfo userInfo = userInfoService.selectById(userSession);
        if(null != userInfo ) {
            records.stream().forEach(item->{
                item.setStoreName(userInfo.getStoreName());
                item.setStoreRemark(userInfo.getStoreRemark());
                item.setTradeStall(userInfo.getTradeStall());
            });
        }

        return PageResult.buildSuccess(page.getTotal(), records);
    }


    //上传报价
    @RequestMapping(value = "/uploadProductDo")
    @ApiOperation(value = "上传报价", notes = "上传报价")
    public JsonResult uploadProductDo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());

        UserInfo userInfo = null;
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        } else {
            userInfo = userInfoService.selectById(userSession);
            request.setAttribute("user", userInfo);
        }

        if (userInfo == null) {
            retMap.put("msg", "数据错误");
            return JsonResult.buildError(retMap);
        }

        if (userInfo.getAuditStatus() == 0) {
            retMap.put("msg", "你还未审核通过，请联系管理员");
            return JsonResult.buildError(retMap);
        }


        String productsStr = request.getParameter("products");
        if (StringUtils.isBlank(productsStr)) {
            retMap.put("msg", "上传的产品为空");
            return JsonResult.buildError(retMap);
        }

        String key = "lock_upload_product_" + userSession;

        if (super.getSession().getAttribute(key) != null) {
            retMap.put("msg", "提交过快");
            return JsonResult.buildError(retMap);
        }

        try {

            super.getSession().setAttribute(key, key);
            productsStr = productsStr.replaceAll("<br/>", "\n").replaceAll("<br>", "\n");

            String products[] = productsStr.split("\\r\\n|\\n|\\r");

            List<OfferProduct> addList = new ArrayList<OfferProduct>();

            Date nowDate = new Date();

            for (String item : products) {

                String offerProduct = item.trim();

                if (StringUtils.isBlank(offerProduct)) {
                    continue;
                }

                String priceStr = null;
                List<String> numList = getFullNumFromString(offerProduct);
                if (numList.size() > 0) {
                    priceStr = numList.get(numList.size() - 1);
                }


                //			EntityWrapper<OfferProduct> wrapper = new EntityWrapper<OfferProduct>();
                //			OfferProduct wProduct = new OfferProduct();
                //			wProduct.setUid(userSession);
                //			wProduct.setOfferProduct(offerProduct);
                //
                //
                //			wrapper.setEntity(wProduct);
                //			List<OfferProduct> list2 = offerProductService.selectList(wrapper);
                //
                //			if(list2!=null && list2.size() > 0){
                //				OfferProduct itemProduct = list2.get(0);
                //				wProduct.setId(itemProduct.getId());
                //				wProduct.setMtime(new Date());
                //				offerProductService.updateById(wProduct);
                //
                //			}else{
                //				OfferProduct newProduct = new OfferProduct();
                //				newProduct.setUid(userSession);
                //				newProduct.setOfferProduct(item.trim());
                //				if(priceStr!=null){
                //					newProduct.setGatherPrice(new BigDecimal(priceStr));
                //				}
                //				addList.add(newProduct);
                //			}

                OfferProduct newProduct = new OfferProduct();
                newProduct.setUid(userSession);
                if (priceStr != null) {
                    newProduct.setProduct(item.trim().replace(priceStr, ""));
                } else {
                    newProduct.setProduct(item.trim());
                }

                newProduct.setOfferProduct(item.trim());
                newProduct.setCtime(nowDate);

                if (priceStr != null) {
                    newProduct.setGatherPrice(new BigDecimal(priceStr));
                }
                addList.add(newProduct);


            }

            if (addList.size() > 0) {
                offerProductService.insertBatch(addList);
                UserInfo upUserInfo = new UserInfo();
                upUserInfo.setUid(userSession);
                upUserInfo.setProductUpdateTime(nowDate);
                userInfoService.updateById(upUserInfo);
            }


        } finally {
            super.getSession().removeAttribute(key);
        }

        EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
        userIntegralEntityWrapper.eq("uid", userSession);
        UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);

        if(null == userIntegral ){
            userIntegral = new UserIntegral();
            userIntegral.setUid(userSession);
            userIntegral.setQuota(10);
            userIntegral.setCreateTime(new Date());
            userIntegral.setUpdateTime(userIntegral.getCreateTime());
            userIntegralService.insert(userIntegral);
        }else{
            userIntegral.setQuota(userIntegral.getQuota()+10);
            userIntegral.setUpdateTime(new Date());
            userIntegralService.updateById(userIntegral);
        }

        UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
        userIntegralRecord.setUid(userSession);
        userIntegralRecord.setQuota(10);
        userIntegralRecord.setCreateTime(new Date());
        userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
        userIntegralRecord.setSource("发布报价");
        userIntegralRecordService.insert(userIntegralRecord);

        request.setAttribute("msg", "产品报价上传成功");
        retMap.put("msg", "产品报价上传成功");
        return JsonResult.buildSuccess(retMap);
    }



    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public JsonResult<String> batchDel(@RequestParam(value = "ids", required = true) String ids) {

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            return JsonResult.buildError("请登录");
        }

        EntityWrapper<OfferProduct> wrapper = new EntityWrapper<OfferProduct>();
        OfferProduct newO = new OfferProduct();


        String[] idms = ids.split(",");

        for (String id : idms) {

            newO.setUid(userSession);
            newO.setId(Integer.valueOf(id));
            wrapper.setEntity(newO);
            offerProductService.delete(wrapper);
        }

        return JsonResult.buildSuccess();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult<String> update(@RequestParam(value = "id") String id,HttpServletRequest request) {

//        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
//        if (userSession == null) {
//            return JsonResult.buildError("请登录");
//        }

        OfferProduct offerProduct = offerProductService.selectById(id);

        if(null != offerProduct){
            String product = request.getParameter("product");

            if(StringUtils.isNotBlank(product)){

                String productsStr = product.replaceAll("<br/>", "\n");
                List<String> numList = getFullNumFromString(productsStr.trim());
                String priceStr = null;

                if (numList.size() > 0) {
                    priceStr = numList.get(numList.size() - 1);
                }

                if (priceStr != null) {
                    offerProduct.setProduct(productsStr.trim().replace(priceStr, "").trim());
                }

                offerProduct.setOfferProduct(productsStr.trim());

                if (priceStr != null) {
                    offerProduct.setGatherPrice(new BigDecimal(priceStr));
                }
                offerProductService.updateById(offerProduct);

            }
        }

        return JsonResult.buildSuccess();
    }

    //删除商品报价
    @RequestMapping(value = "/delAllProduct")
    @ApiOperation(value = "删除商品报价", notes = "删除商品报价")
    public JsonResult<String> delAllProduct(HttpServletRequest request, HttpServletResponse response) {
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            return JsonResult.buildError("请登录");
        }

        EntityWrapper<OfferProduct> wrapper = new EntityWrapper<OfferProduct>();
        OfferProduct wProduct = new OfferProduct();
        wProduct.setUid(userSession);
        wrapper.setEntity(wProduct);
        offerProductService.delete(wrapper);

        return JsonResult.buildSuccess("删除成功");

    }

    @RequestMapping(value = "/upPwd")
    public JsonResult upPwd(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());

        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        return JsonResult.buildSuccess(retMap);
    }

    @RequestMapping(value = "/upPwdDo")
    public JsonResult upPwdDo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        String homeDomain = (String) request.getSession().getAttribute(SystemParameterEnum.HOME_DOMAIN_NAME.getName());

        UserInfo userInfo = null;
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        } else {
            userInfo = userInfoService.selectById(userSession);
            retMap.put("user", userInfo);
        }

        if (userInfo == null) {
            retMap.put("msg", "数据错误");
            return JsonResult.buildError(retMap);
        }

        String oldPwd = request.getParameter("oldPwd");//密码

        String newPwd = request.getParameter("newPwd");

        String newPwd2 = request.getParameter("newPwd2");//

        if (StringUtils.isBlank(oldPwd)) {
            retMap.put("msg", "原密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isBlank(newPwd)) {
            retMap.put("msg", "新密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (!newPwd.equals(newPwd2)) {
            retMap.put("msg", "新密码和确认新密码不一致");
            return JsonResult.buildError(retMap);
        }

        String oldPwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + oldPwd);

        String newPwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + newPwd2);

        if (!oldPwdString.equals(userInfo.getPwd())) {
            retMap.put("msg", "原密码不正确");
            return JsonResult.buildError(retMap);
        }

        UserInfo newUser = new UserInfo();
        newUser.setUid(userInfo.getUid());
        newUser.setPwd(newPwdString);
        userInfoService.updateById(newUser);
        request.getSession().setAttribute("op_msg", "密码修改成功");
        retMap.put("op_msg", "密码修改成功");
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 15天内折线图
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/chart")
    @ApiOperation(value = "15天内折线图", notes = "15天内折线图")
    public JsonResult chart(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> retMap = new HashMap<>();
        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String uid = request.getParameter("uid"); //商户uid

        if (StringUtils.isBlank(uid)) {
            retMap.put("msg", "商户uid为空");
            return JsonResult.buildError(retMap);
        }
        String product = request.getParameter("product"); //采集到的产品名称

        if (StringUtils.isBlank(product)) {
            retMap.put("msg", "采集到的产品名称为空");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
        userInfoWrapper.eq("uid", uid);
        UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

        if (null == userInfo) {
            retMap.put("msg", "商户uid不存在");
            return JsonResult.buildError(retMap);
        }

        final long days = 15;

        EntityWrapper<OfferProduct> offerWrapper = new EntityWrapper<OfferProduct>();
        offerWrapper.eq("uid", uid);
        offerWrapper.eq("product", product);
        Date now = new Date();
        offerWrapper.ge("ctime", new Date(now.getTime() - days * 24 * 60 * 60 * 1000));//最近15天报价
        offerWrapper.orderBy("ctime", true);
        List<OfferProduct> offerProducts = offerProductService.selectList(offerWrapper);


        List<OfferProduct> retOfferProduct = new ArrayList<>();

        for (long i = 0; i <= days; i++) {

            final int index = (int) i;

            retOfferProduct.add(offerProducts.stream().filter(f -> index == (now.getTime() - f.getCtime().getTime()) / 1000 / 3600 / 24)
                    .sorted(Comparator.comparing(OfferProduct::getCtime).reversed())
                    .findFirst().orElse(new OfferProduct()));

        }

        retMap.put("offerProducts", retOfferProduct);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 词条详情
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/entry_detial")
    public JsonResult entry_detial(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String offerProductId = request.getParameter("offer_product_id"); //采集到的产品名称

        if (StringUtils.isBlank(offerProductId)) {
            retMap.put("msg", "产品id为空 offset_product里面的id");
            return JsonResult.buildError(retMap);
        }


        EntityWrapper<Entry> entityWrapper = new EntityWrapper();

        entityWrapper.eq("uid", userSession);
        entityWrapper.eq("offer_product_id", offerProductId);

        Entry entry = entryService.selectOne(entityWrapper);

        retMap.put("entry", entry);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 词条更新
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/entry_update")
    public JsonResult entry_update(@RequestParam(value = "img",required = false) MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String offerProductId = request.getParameter("offer_product_id"); //采集到的产品名称

        if (StringUtils.isBlank(offerProductId)) {
            retMap.put("msg", "产品id为空 offset_product里面的id");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<OfferProduct> offerProductEntityWrapper = new EntityWrapper();
        offerProductEntityWrapper.eq("id", offerProductId);
        OfferProduct offerProduct = offerProductService.selectOne(offerProductEntityWrapper);
        if (null == offerProduct) {
            retMap.put("msg", "无效的产品id,offset_product里面的id");
            return JsonResult.buildError(retMap);
        }


        String name = request.getParameter("name");
        String batch_number = request.getParameter("batch_number");
        String barcode = request.getParameter("barcode");
        String gross_weight = request.getParameter("gross_weight");
        String net_weight = request.getParameter("net_weight");
        String type = request.getParameter("type");
        String efficacy = request.getParameter("efficacy");
        String place = request.getParameter("place");
        String shelf_life = request.getParameter("shelf_life");
        String product_time = request.getParameter("product_time");
        String expire_time = request.getParameter("expire_time");


        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            EntityWrapper<Entry> entityWrapper = new EntityWrapper();

            entityWrapper.eq("uid", userSession);
            entityWrapper.eq("offer_product_id", offerProductId);

            Entry entry = entryService.selectOne(entityWrapper);

            String newFileName = null;
            if (multipartFile != null && !multipartFile.isEmpty()) {
                // 检查是否是图片
                try {
                    BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
                    if (bi == null) {
                        retMap.put("msg", "请上传图片格式的文件");
                        return JsonResult.buildError(retMap);
                    }
                } catch (IOException e) {
                    retMap.put("msg", "请上传图片格式的文件");
                    return JsonResult.buildError(retMap);
                }

                String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

                if (StringUtils.isBlank(filePath)) {
                    retMap.put("msg", "未配置filePath");
                    return JsonResult.buildError(retMap);
                }
                filePath = filePath + File.separator;

                try {
                    InputStream inputStream = multipartFile.getInputStream();
                    String fileName = multipartFile.getOriginalFilename();
                    Path directory = Paths.get(filePath);
                    if (!Files.exists(directory)) {
                        Files.createDirectories(directory);
                    }
                    newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                    long copy = Files.copy(inputStream, directory.resolve(newFileName));

                    Thumbnails.of(filePath + newFileName).scale(0.7f).toFile(filePath + newFileName);//按比例缩小

                } catch (Exception e) {
                    retMap.put("msg", "图片上传失败");
                    return JsonResult.buildError(retMap);
                }
            }


            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if(entry == null ){
                entry = new Entry();
                entry.setName(name);
                entry.setUid(userSession);
                entry.setOfferProductId(Integer.parseInt(offerProductId));
                entry.setStatus(1);
                entry.setBarcode(barcode);
                entry.setBatchNumber(batch_number);
                entry.setCreateTime(new Date());
                entry.setImg(newFileName);
                entry.setGrossWeight(Integer.parseInt(gross_weight));
                entry.setNetWeight(Integer.parseInt(net_weight));
                entry.setEfficacy(efficacy);
                entry.setShelfLife(Integer.parseInt(shelf_life));
                entry.setType(type);
                if (StringUtils.isNotBlank(product_time)) {
                    entry.setProductTime(formater.parse(product_time));
                }
                if (StringUtils.isNotBlank(expire_time)) {
                    entry.setExpireTime(formater.parse(expire_time));
                }

                entry.setUpdateTime(entry.getCreateTime());
                entry.setPlace(place);
                entryService.insert(entry);
            }else{
                entry.setName(name);
                entry.setUid(userSession);
                entry.setOfferProductId(Integer.parseInt(offerProductId));
                entry.setStatus(1);
                entry.setBarcode(barcode);
                entry.setBatchNumber(batch_number);
                entry.setImg(newFileName);
                entry.setGrossWeight(Integer.parseInt(gross_weight));
                entry.setNetWeight(Integer.parseInt(net_weight));
                entry.setEfficacy(efficacy);
                entry.setShelfLife(Integer.parseInt(shelf_life));
                entry.setType(type);
                if (StringUtils.isNotBlank(product_time)) {
                    entry.setProductTime(formater.parse(product_time));
                }
                if (StringUtils.isNotBlank(expire_time)) {
                    entry.setExpireTime(formater.parse(expire_time));
                }
                entry.setUpdateTime(new Date());
                entry.setPlace(place);
                entryService.updateById(entry);


                EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
                userIntegralEntityWrapper.eq("uid", userSession);
                UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);

                Date now = new Date();
                if(null == userIntegral ){
                    userIntegral = new UserIntegral();
                    userIntegral.setUid(userSession);
                    userIntegral.setQuota(10);
                    userIntegral.setCreateTime(now);
                    userIntegral.setUpdateTime(userIntegral.getCreateTime());
                    userIntegralService.insert(userIntegral);
                }else{
                    userIntegral.setQuota(userIntegral.getQuota()+10);
                    userIntegral.setUpdateTime(now);
                    userIntegralService.updateById(userIntegral);
                }
            }
            UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
            userIntegralRecord.setUid(userSession);
            userIntegralRecord.setQuota(10);
            userIntegralRecord.setCreateTime(new Date());
            userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
            userIntegralRecord.setSource("词条");
            userIntegralRecordService.insert(userIntegralRecord);
        } catch (Exception e) {
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        } finally {
            lock.unlock();
        }

        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 置顶
     */
    @RequestMapping(value = "/top_product")
    @ApiOperation(value = "置顶", notes = "置顶")
    public JsonResult top_product(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String offerProductId = request.getParameter("offer_product_id"); //采集到的产品名称
        if (StringUtils.isBlank(offerProductId)) {
            retMap.put("msg", "产品id为空 offset_product里面的id");
            return JsonResult.buildError(retMap);
        }

        int num = 0;
        if(StringUtils.isNotBlank(request.getParameter("num"))){
            num = Integer.parseInt(request.getParameter("num")) * 10;
        }


        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            EntityWrapper<OfferProduct> offerProductEntityWrapper = new EntityWrapper();

            offerProductEntityWrapper.eq("uid", userSession);
            offerProductEntityWrapper.eq("id", offerProductId);

            OfferProduct offerProduct = offerProductService.selectOne(offerProductEntityWrapper);

            if(null == offerProduct ){
                retMap.put("msg", "非本商户下的报价商品");
                return JsonResult.buildError(retMap);
            }
            offerProduct.setTopTime(new Date());
            offerProductService.updateById(offerProduct);

            EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
            userIntegralEntityWrapper.eq("uid", userSession);
            UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);

            if(null == userIntegral ){
                userIntegral = new UserIntegral();
                userIntegral.setUid(userSession);
                userIntegral.setQuota(0);
                userIntegral.setCreateTime(new Date());
                userIntegral.setUpdateTime(userIntegral.getCreateTime());
                userIntegralService.insert(userIntegral);
            }else{
                userIntegral.setQuota(userIntegral.getQuota()-num < 0 ? 0 :userIntegral.getQuota()- num);
                userIntegral.setUpdateTime(new Date());
                userIntegralService.updateById(userIntegral);
            }
            UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
            userIntegralRecord.setUid(userSession);
            userIntegralRecord.setQuota(userIntegral.getQuota());
            userIntegralRecord.setCreateTime(new Date());
            userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
            userIntegralRecord.setSource("置顶推广");
            userIntegralRecordService.insert(userIntegralRecord);
        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }


    /**
     *  用户积分记录
     */
    @RequestMapping(value = "/record")
    @ApiOperation(value = "用户积分记录", notes = "用户积分记录")
    public JsonResult record(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<UserIntegralRecord> userIntegralRecordEntityWrapper = new EntityWrapper();
        userIntegralRecordEntityWrapper.eq("uid", userSession);
        List<UserIntegralRecord> userIntegralRecords = userIntegralRecordService.selectList(userIntegralRecordEntityWrapper);
        retMap.put("userIntegralRecords",userIntegralRecords);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     *  购买会员
     */
    @RequestMapping(value = "/buyVip")
    @ApiOperation(value = "购买会员", notes = "购买会员")
    public JsonResult buyVip(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> retMap = new HashMap<>();

        Integer userSession = (Integer) super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if (userSession == null) {
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
        userIntegralRecord.setUid(userSession);
        userIntegralRecord.setQuota(50);
        userIntegralRecord.setCreateTime(new Date());
        userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
        userIntegralRecord.setSource("购买会员");
        userIntegralRecordService.insert(userIntegralRecord);

        return JsonResult.buildSuccess(retMap);
    }

    @PutMapping(value = "/user-pwd")
    @ApiOperation(value = "找回密码", notes = "找回密码")
    public JsonResult userPwd(@RequestBody RegisterUseRequest registerUseRequest) {

        Map<String, Object> retMap = new HashMap<>();

        String phone = registerUseRequest.getPhone();//手机号
        String pwd = registerUseRequest.getPwd();//密码
        String verifyCode = registerUseRequest.getVerifyCode();//短信验证码

        if (StringUtils.isEmpty(phone)) {
            retMap.put("msg", "手机号不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(pwd)) {
            retMap.put("msg", "密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(verifyCode)) {
            retMap.put("msg", "验证码");
            return JsonResult.buildError(retMap);
        }


        //判断短信验证码
        final Object cacheValue = CacheUtils.get(SMS_PREFIX + phone);
        if (null == cacheValue) {
            retMap.put("msg", "验证码已失效");
            return JsonResult.buildError(retMap);
        }

        String code = (String) cacheValue;

        if(!verifyCode.equals(code)){
            retMap.put("msg", "请输入正确的验证码");
            return JsonResult.buildError(retMap);
        }


        EntityWrapper<UserInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", phone);

        final UserInfo userInfo = userInfoService.selectOne(wrapper);


        if (null == userInfo) {
            retMap.put("msg", "账号为注册");
            return JsonResult.buildError(retMap);
        }


        String pwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + pwd);

        userInfo.setPwd(pwdString);

        userInfoService.updateById(userInfo);

        return JsonResult.buildSuccess(retMap);

    }



    @PostMapping(value = "/register")
    @ApiOperation(value = "手机注册", notes = "注册")
    public JsonResult register(@RequestBody RegisterUseRequest registerUseRequest) {

        Map<String, Object> retMap = new HashMap<>();

        String phone = registerUseRequest.getPhone();//手机号
        String pwd = registerUseRequest.getPwd();//密码
        String verifyCode = registerUseRequest.getVerifyCode();//短信验证码

        if (StringUtils.isEmpty(phone)) {
            retMap.put("msg", "手机号不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(pwd)) {
            retMap.put("msg", "密码不能为空");
            return JsonResult.buildError(retMap);
        }

        if (StringUtils.isEmpty(verifyCode)) {
            retMap.put("msg", "验证码");
            return JsonResult.buildError(retMap);
        }


        EntityWrapper<UserInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", phone);

        int count = userInfoService.selectCount(wrapper);

        if (count > 0) {
            retMap.put("msg", "手机号已注册");
            return JsonResult.buildError(retMap);
        }


        //判断短信验证码
        final Object cacheValue = CacheUtils.get(SMS_PREFIX + phone);
        if (null == cacheValue) {
            retMap.put("msg", "验证码已失效");
            return JsonResult.buildError(retMap);
        }

        String code = (String) cacheValue;

        if(!verifyCode.equals(code)){
            retMap.put("msg", "请输入正确的验证码");
            return JsonResult.buildError(retMap);
        }



        String pwdString = MD5.MD5EncodeUTF8(Constants.PWD_MD5_KEY + pwd);

        UserInfo newUser = new UserInfo();
        newUser.setUserType(UserInfo.USER_KIND);
        newUser.setMobile(phone);
        newUser.setPwd(pwdString);
        newUser.setLoginStatus(1);
        newUser.setWeixin("");
        newUser.setWeixinImg("");
        newUser.setLogoImg("");
        newUser.setTradeStall("");
        newUser.setStoreName("");
        newUser.setStoreRemark("");
        newUser.setRandom(RandomStringUtils.randomNumeric(9));

        boolean result = userInfoService.insert(newUser);
        if (result) {
            newUser = userInfoService.selectById(newUser.getUid());
            super.getSession().setAttribute(UserInfo.USER_SESSION_UID, newUser.getUid());
            retMap.put("user", newUser);
            return JsonResult.buildSuccess(retMap);
        }
        return JsonResult.buildSuccess(retMap);
    }
}


